package com.nice.app.util.json;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.annotation.PostConstruct;

import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.AnnotationIntrospector;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.SerializerProvider;
import org.codehaus.jackson.map.introspect.VisibilityChecker;
import org.codehaus.jackson.map.ser.CustomSerializerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.ConversionService;

/**
 * A custom Jackson ObjectMapper that installs JSON serialization/deserialization support
 * for properties annotated with Spring format annotations such as @DateTimeFormat and @NumberFormat.
 */
public class ConversionServiceAwareObjectMapper extends ObjectMapper {
	
	private String mask = "yyyy-MM-dd HH:mm:ss";

	@Autowired
	public ConversionServiceAwareObjectMapper(ConversionService conversionService) {
		AnnotationIntrospector introspector = AnnotationIntrospector.pair(new FormatAnnotationIntrospector(conversionService), DEFAULT_ANNOTATION_INTROSPECTOR);
		SerializationConfig sconfig = new SerializationConfig(DEFAULT_INTROSPECTOR, introspector,  VisibilityChecker.Std.defaultInstance(), null, null, _typeFactory, null);
		DeserializationConfig dconfig = new DeserializationConfig(DEFAULT_INTROSPECTOR, introspector,  VisibilityChecker.Std.defaultInstance(), null, null, _typeFactory, null);
		setSerializationConfig(sconfig);
		setDeserializationConfig(dconfig);
		
	}
	
//	@PostConstruct
//	public void afterPropertiesSet() throws Exception {
//		super.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);
//
//        //this one doesn't work at all, it's necessary to create and register a factory
//		//getSerializationConfig().withDateFormat(new SimpleDateFormat(mask));
//
//        //I am using Jackson 1.9 asl
//		CustomSerializerFactory factory = new CustomSerializerFactory();
//		factory.addSpecificMapping(Date.class, new JsonSerializer<Date>() {
//
//			@Override
//			public Class<Date> handledType() { return Date.class; }
//
//			@Override
//			public void serialize(Date value, JsonGenerator jgen,
//					SerializerProvider provider) throws IOException,
//					JsonProcessingException {
//
//				jgen.writeString(new SimpleDateFormat(mask).format(value));
//			}});
//                           this.setSerializerFactory(factory);
//	}

	public void setMask(String mask) {
		this.mask = mask;
	}
}
